; NAME:
; gauge_flux_extract_file_info
;
; PURPOSE:
; Opens a netcdf file and reads in the dimension and variable names and info.
; If the file is zipped then it unzips the file extracts the info and deletes the unzipped version
;
; CATEGORY:
; regridding
;
; CALLING SEQUENCE:
; gauge_flux_extract_file_info, FileName, DimNames,DimSizes,  VarNames, VarTypes, VarDims
;
; INPUTS:
; FileName
;
; OUTPUTS:
; DimNames = String array containing the dimension names
; DimsSizes = Array containing the dimension sizes
; VarInfo = Hash keyed by varibale name containing
;            the variable names
;            the vaiable types
;            the dimension of each variable
;            the names of the attributes of each variable
;            the attributed for each variable
;
; LON_NCNAME = String containing the name of the lon variable
; LAT_NCNAME = String containing the name of the lat variable
; FLUX_NCNAME = String containing the name of the flux variable
; DATE_NCNAME = String containing the name of the date variable
; DATESEC_NCNAME = String containing the name of the datsec variable
; PS_NCNAME = String containing the name of the surface pressure variable
; SKIP_PS = Skip the PS section
; GLOBAL_ATTS = Global attributes
;
; SIDE EFFECTS:
;
; RESTRICTIONS:
;
; PROCEDURE:
;
; MODIFICATION HISTORY:
;   Written Feb 12, 2014 by as13988

pro gauge_flux_extract_file_info, FileName, DimNames, DimSizes, VarInfo, LON_NCNAME = lon_ncname,$
  LAT_NCNAME = lat_ncname, FLUX_NCNAME = flux_ncname,  DATE_NCNAME = date_ncname, DATESEC_NCNAME = datesec_ncname, $
  PS_NCNAME = PS_ncname, SKIP_PS =Skip_PS, GLOBAL_ATTS = Global_Atts
  
  ; set unzipped flag
  unzipped_flag = 0
  
  ; Check if it's zipped/gzipped and if so zip/gunzip it
  Endings = ['gz','zip']
  Key = where(strmatch(Endings, (strsplit(filename,'.',/EXTRACT))[-1]))
  
  Case (Key) of
  
    ; gunzip
    0: begin
      OutFileName = strjoin((strsplit(filename,'.',/EXTRACT))[0:-2],'.')
      FILE_GUNZIP, FileName, OutFileName, /verbose
      ;set unzipped flag
      unzipped_flag = 1
    end
    
    ; unzip
    1: begin
      OutFileName = strjoin((strsplit(filename,'.',/EXTRACT))[0:-2],'.')
      FILE_UNZIP, FileName, OutFileName, /verbose
      ;set unzipped flag
      unzipped_flag = 1
    end
    
    ; Not zipped or unzipped
    else: begin
      OutFileName = FileName
    end
    
  endcase
  
  
  ; open the file
  FileID  = NCDF_OPEN(OutFileName)
  
  ; Extract the number of dimensions, variables etc
  FileInfo = NCDF_INQUIRE(FileID)
  NoDims = FileInfo.ndims
  NoVars = FileInfo.nvars
  NoGlobalAtts = FileInfo.NGATTS
  
  if noglobalatts gt 0 then begin
  GlobalAttNames = strarr(NoGlobalAtts)
  GlobalAtts = strarr(NoGlobalAtts)

  
  ; Extract the global variables
  for i = 0L, NoGlobalAtts-1 do begin
  
    Name_i = NCDF_ATTNAME(fileid, /GLOBAL, i)
    NCDF_ATTGET, fileid, /GLOBAL, name_i, GlobalAtt_i
    
    GlobalAttNames[i] = Name_i
    GlobalAtts[i] = string(GlobalAtt_i)
    
  endfor
  
  Global_Atts = {Names : GlobalAttNames, Atts: GlobalAtts}
  
  endif else begin
  Globa_lAtts = ''
endelse
  
  ; Can then extract information about each dimension/variable using the index
  ; Extract the dimension names and info
  DimNames = strarr(NoDims)
  DimSizes = dblarr(NoDims)
  
  for j = 0L, NoDims-1 do begin
    ncdf_diminq, FileId, j, DummyNames, DummySize
    DimNames[j] = DummyNames
    DimSizes[j] = DummySize
    
  endfor
  
  ; Extract the variable names and info
  VarInfo = hash() ; use a hash as the dimensions will vary with the variable
  
  for j = 0L, NoVars-1 do begin
    ; Extract information about the variable
    dummy = ncdf_varinq(FileId, j)
    
    ; Create a nulls to store the atributes name and the atribute
    AttNames = !null
    Atts = !null
    
    for k = 0L, Dummy.NAtts-1 do begin
      ; Extract the name of the attribute
      AttName_k = NCDF_ATTNAME(FileId, j, k)
      NCDF_ATTGET, FileId, dummy.name , AttName_K, Att_k
      AttNames = [AttNames, AttName_k]
      Atts = [Atts, string(Att_k)]
      
    endfor
    
    if dummy.natts eq 0 then begin
      AttNames = 'No attributes'
      Atts = 'No attributes'
    endif
    
    ; Store the information in a structure
    ; Ultimately want to end up with a hash of structures
    
    Dummy_struct = {Name : Dummy.name, $
      Types : Dummy.DataType, $
      Dimension : DimSizes[Dummy.dim], $
      AttName : AttNames, $
      Attributes : Atts}
      
    VarInfo[Dummy.name] = Dummy_struct
    
  endfor
  
  VarNames = VarInfo.Keys()
  VarNames = VarNames.toarray()
  
  lon_ncname = VarNames[where(strmatch(VarNames, '*lon*', /FOLD_CASE), count_lon)]
  lat_ncname = VarNames[where(strmatch(VarNames, '*lat*', /FOLD_CASE), count_lat)]
  if N_elements(flux_ncname) eq 0 then flux_ncname = VarNames[where(strmatch(VarNames, '*flux*', /FOLD_CASE), count_flux)] $
  else flux_ncname = VarNames[where(strmatch(VarNames, Flux_ncname, /FOLD_CASE), count_flux)]
  date_ncname = VarNames[where(strmatch(VarNames, 'date', /FOLD_CASE), count_date)]
  if N_elements(datesec_ncname) eq 0 then datesec_ncname = VarNames[where(strmatch(VarNames, 'datesec', /FOLD_CASE), count_datesec)] else count_datesec = 1
  If count_datesec eq 0 then datesec_ncname = ''
  if N_elements(PS_ncname) eq 0 then PS_ncname = VarNames[where(strmatch(VarNames, 'PS', /FOLD_CASE), count_PS)] else count_PS = 1
  
  
  ; Need to check the above matches
  ; and select them manually if they're not given
  if count_lon ne 1 then begin
  
    print, 'Found : ' + strtrim(count_lon,2) + ' matches for lon'
    Print, 'Give index from below list to select lon variable'
    print, strtrim(indgen(n_elements(VarNames))) + ' : ' + VarNames
    READ, VarName_index, PROMPT='Enter index: '  ; Read input from the keyboard.
    lon_ncname = lon_ncname[VarName_index]
    
  endif
  
  if count_lat ne 1 then begin
  
    print, 'Found : ' + strtrim(count_lat,2) + ' matches for lat'
    Print, 'Give index from below list to select lat variable'
    print, strtrim(indgen(n_elements(VarNames))) + ' : ' + VarNames
    READ, VarName_index, PROMPT='Enter index: '  ; Read input from the keyboard.
    lat_ncname = VarNames[VarName_index]
    
  endif
  
  if count_flux ne 1 then begin
  
    print, 'Found : ' + strtrim(count_flux,2) + ' matches for flux'
    Print, 'Give index from below list to select variable you wish to regrid'
    print, strtrim(indgen(n_elements(VarNames))) + ' : ' + VarNames
    READ, VarName_index, PROMPT='Enter index: '  ; Read input from the keyboard.
    flux_ncname = VarNames[VarName_index]
    
  endif
  
  ; Want to check if the flux variable is 3d or not
  ; if it's not 3D then set the Skip_PS keyword
  
  ;If n_elements( ( ( (varinfo[flux_ncname]).tostruct() ).(0)).Dimension) le 3 then Skip_PS = 1
  If n_elements((varinfo[strjoin(flux_ncname)]).dimension) le 3 then Skip_PS = 1
  
  
  if count_date ne 1 then begin
  
    print, 'Found : ' + strtrim(count_date,2) + ' matches for flux'
    Print, 'Give index from below list to select date variable'
    print, strtrim(indgen(n_elements(VarNames))) + ' : ' + VarNames
    READ, VarName_index, PROMPT='Enter index: '  ; Read input from the keyboard.
    date_ncname = VarNames[VarName_index]
    
  endif
  
  if count_datesec ne 1 then begin
  
    print, 'Found : ' + strtrim(count_datesec,2) + ' matches for flux'
    Print, 'Give index from below list to select datesec variable'
    print, strtrim(indgen(n_elements(VarNames))) + ' : ' + VarNames
    READ, VarName_index, PROMPT='Enter index: '  ; Read input from the keyboard.
    datesec_ncname = VarNames[VarName_index]
    
  endif
  
  if count_PS ne 1 and keyword_set(SKIP_PS) eq 0 then begin
  
    print, 'Found : ' + strtrim(count_PS,2) + ' matches for surface pressure'
    Print, 'Give index from below list to select surface pressure variable'
    print, strtrim(indgen(n_elements(VarNames))) + ' : ' + VarNames
    READ, VarName_index, PROMPT='Enter index: '  ; Read input from the keyboard.
    PS_ncname = VarNames[VarName_index]
    
  endif
  
  
  ; If the file had to be unzipped to extract the data then delete the unzipped file
  if unzipped_flag eq 1 then begin
    OutFileName = strjoin((strsplit(filename,'.',/EXTRACT))[0:-2],'.')
    FILE_DELETE, OUtFileName
    
  endif
  
  
end